package com.google.code.maven.plugin.http.client.transformer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.maven.plugin.MojoExecutionException;

import com.google.code.maven.plugin.http.client.HttpEntityUtils;

/**
 * <h1>abstract class for all {@link HttpEntity} concrete {@link Transformer}</h1>
 * 
 * @author Nadim Benabdenbi
 * @version 1.0
 * @since JDK1.6
 * 
 * @see Transformer
 * @see AbstractTransformer
 * @see HttpEntity
 */
public abstract class AbstractHttpEntityTransformer<Target> extends AbstractTransformer<HttpEntity, Target> {
	
	@Override
	protected final Target doTransform(HttpEntity entity) throws MojoExecutionException {
		log.debug("Response content length: " + entity.getContentLength());
		log.debug("Response content encoding: " + entity.getContentEncoding());
		log.debug("Response content type: " + entity.getContentType());
		log.debug("Response stream encoding set to: " + HttpEntityUtils.getEncoding(entity, log));
		try {
			return transform(entity);
		} catch (Throwable t) {
			if (t instanceof MojoExecutionException) {
				throw (MojoExecutionException) t;
			} else {
				throw new MojoExecutionException("failed to transform", t);
			}
		}
	}
	
	/**
	 * http content reader getter
	 * 
	 * @param entity
	 *            the http entity
	 * @return the reader derived from the entity input stream
	 * 
	 * @throws IllegalStateException
	 *             when the entity is not resulting from a http response
	 * @throws IOException
	 *             in case of network failure
	 */
	protected final BufferedReader getContentReader(HttpEntity entity) throws IllegalStateException, IOException {
		return new BufferedReader(new InputStreamReader(entity.getContent(), HttpEntityUtils.getEncoding(entity, log)));
	}
	
	/**
	 * http entity transformation
	 * 
	 * @param entity
	 *            the http entity to transfom
	 * @return
	 * @throws Exception
	 *             in case of an unexpected transformation error
	 */
	protected abstract Target transform(HttpEntity entity) throws Exception;
	
}
